package com.guochenglang.www.controller;

import com.guochenglang.www.pojo.User;
import com.guochenglang.www.service.FileService;
import com.guochenglang.www.service.UserService;
import com.guochenglang.www.util.MyDependency;
import com.guochenglang.www.util.ObjectTurnKey;
import com.guochenglang.www.util.RequestReCodeUtil;
import com.guochenglang.www.web.result.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件Controller层
 *
 * @author GuoChenglang
 */

public class MyFilesController {
    private static final FileService FILE_SERVICE = MyDependency.returnObject(FileService.class);
    private static final UserService USER_SERVICE = MyDependency.returnObject(UserService.class);

    /**
     * 添加文章附件
     */
    public static Result articleImage(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, SQLException, InterruptedException, IllegalAccessException {
        Result result = new Result();
        //获取前端附件信息
        List<FileItem> items = analysis(req, resp);
        if (items == null || items.isEmpty()) {
            return Result.noResult();
        }
        Integer articleId = 0;
        for (FileItem item : items) {
            //信息为普通字段
            if (item.isFormField()) {
                //通过方法获取文章id
                articleId = FILE_SERVICE.processFormField(item);
            } else {
                //附件为文件字段
                result = FILE_SERVICE.processFileUpload(item, req);
                String url = ObjectTurnKey.objectTurnKeyToString((Object[]) result.getData());
                //将附件连接添加进数据库
                FILE_SERVICE.articleImageUpload(articleId, url);
            }
        }
        return Result.result(null);
    }

    /**
     * 添加头像附件
     */
    public static Result headImage(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        Result result = new Result();
        //获得附件信息
        List<FileItem> items = analysis(req, resp);
        if (items == null || items.isEmpty()) {
            return Result.noResult();
        }
        Integer userId = 0;
        for (FileItem item : items) {
            //普通字段
            if (item.isFormField()) {
                //获得用户id
                userId = FILE_SERVICE.processFormField(item);
            } else {
                //文件字段
                System.out.println(userId);
                result = FILE_SERVICE.processFileUpload(item, req);
                String url = ObjectTurnKey.objectTurnKeyToString((Object[]) result.getData());
                //将头像连接添加进数据库
                User setImage = new User();
                setImage.setHeadImage(url);
                USER_SERVICE.updateUser(userId, setImage);
                return Result.result(null);
            }
        }
        return Result.result(null);
    }

    /**
     * 获取item的方法封装
     */
    private static List<FileItem> analysis(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        //判断是否文件上传请求
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (!isMultipart) {
            //返回错误信息
            return null;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //集合收容解析内容
        List<FileItem> items = new ArrayList<>();
        //将文件放到容器中
        try {
            items = upload.parseRequest(req);
            return items;
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }
    }
}
